<script>
import { api } from '@/api';
import { call } from '@/chat/call';
import { useAppStore } from '@/stores/app';
import useContactsStore from '@/stores/contacts';
import { mapStores } from 'pinia';
import { Button, Dialog, Loading, SwipeCell, Toast } from 'vant';

export default {
  props: {
    searchText: {
      type: String,
      default: ''
    },
    searchResult: {
      type: Array,
      default: () => []
    }
  },
  components: {
    SwipeCell,
    Button,
    Loading
},
  computed: {
    ...mapStores(useAppStore, useContactsStore),
    searched() {
      if (this.searchText) {
        // 去重，根据 id
        return this.contactsStore.friends.concat(this.searchResult).filter((item, index, arr) => arr.findIndex(t => t.id === item.id) === index).filter(item => {
          return item.friend_name?.includes?.(this.searchText) || item.nick_name?.includes?.(this.searchText) || String(item.uid)?.includes?.(this.searchText)
        })
      } else {
        return this.contactsStore.friends
      }
    }
  },
  data() {
    return {
    }
  },
  methods: {
    async handleChat(friend) {
      const { friend_name: username, nickName } = friend

      if (!friend.isFriend) {
        return Dialog.confirm({
          title: '提示',
          message: '是否申请添加好友？',
        }).then(type => {
          if (type === 'confirm') {
            api.friends.applyAdd({ friendName: username }).then(({ success, msg }) => {
              if (success) {
                Toast.success({ message: '已发送申请' })
                this.getList()
                this.handleSearch()
              } else {
                Toast.fail({ message: msg ?? '申请失败' })
              }
            })
          }
        }).catch(() => { })
      }

      if (this.contactsStore.friends.every(({ friend_name }) => friend_name !== username)) {
        await api.friends.add({ friendName: username })
      }

      this.$router.push({ path: `/chat/${username}`, query: { name: nickName } })
    },
    async handleCall(username) {
      call(username)
    },
    async handleRemove(username) {
      Dialog.confirm({
        title: '提示',
        message: '确定要删除吗？'
      }).then(async () => {
        const { success, msg } = await api.friends.remove({ friendName: username })
        if (success) {
          Toast.success({ message: '删除成功' })
          this.getList()
          this.handleSearch()
        } else {
          Toast.fail({ message: msg ?? '删除失败' })
        }
      })
    },
  },
}
</script>

<template>
  <div class="contacts-list">
    <div class="contacts-list-title">
      <span>好友列表</span>
      <Loading v-if="contactsStore.fridensLoading" size="16" />
    </div>
    <div v-if="searched.length === 0" class="contacts-list-empty">暂无</div>
    <SwipeCell
      v-for="item in searched"
      :key="item.username"
      :disabled="contactsStore.friends.every(({ user_name }) => user_name !== item.user_name)"
    >
      <div class="contacts-item" @click="handleChat(item)">
        <div class="contacts-item-info">
          <img class="contacts-item-avatar" :src="`/${item.avatar_url}`" alt="">
          <div class="contacts-item-name">
            <div class="contacts-item-nickname">{{ item.nickName }}</div>
            <div class="contacts-item-uid">UName: {{ item.friend_name }}</div>
          </div>
        </div>

        <img class="contacts-item-send" src="../assets/icons/send.png" alt="">
      </div>

      <template #right>
        <Button square type="primary" text="语音" style="height: 100%;" @click="handleCall(item.friend_name)" />
        <Button square type="danger" text="删除" style="height: 100%;" @click="handleRemove(item.friend_name)" />
      </template>
    </SwipeCell>
  </div>
</template>
